﻿//20140307.. ..Pou：增加出現載入失敗為空白時，需要通知為載入失敗的事件。
//20140422.. ..Pou：加入防止scroll與zoom的功能。
//20140427.. ..Pou：解決按下廣告後，沒有辦法正確導向指定Task的問題。
//20140505.. ..Pou：增加沒有網路時的判斷。增加設定是否自動更新廣告的問題。

using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Navigation;
using Windows.Storage;
using System.IO;
using LinqToVisualTree;
using Microsoft.Phone.Net.NetworkInformation;
using System.Windows.Threading;

namespace com.poumason.WP.HodoAdWP8
{
    public partial class HodoAdControl : UserControl, IDisposable
    {
        public Uri currentUri;

        public event NavigationFailedEventHandler AdFailed;
        //20140307.. ..Pou：增加出現載入失敗為空白時，需要通知為載入失敗的事件。
        public event EventHandler AdError;
        private DispatcherTimer gRefreshTimer = null;

        public string AppID { get; set; }

        //20140505.. ..Pou：增加設定是否自動更新廣告的問題。
        private bool gAudoRefresh = false;
        public bool AutoRefresh
        {
            get { return gAudoRefresh; }
            set { gAudoRefresh = value; }
        }

        public HodoAdControl()
        {
            InitializeComponent();
            //20140422.. ..Pou：加入防止scroll與zoom的功能。
            new WebBrowserHelper(MiniBrowser, true);
        }

        #region 處理Script觸發的事件
        void Browser_ScriptNotify(object sender, NotifyEventArgs e)
        {
            if (e.Value.ToLower().Contains("http") == true)
            {
                //20140427.. ..Pou：解決按下廣告後，沒有辦法正確導向指定Task的問題。
                TaskOSBrowser(new Uri(e.Value, UriKind.Absolute));
            }
        }
        #endregion

        void Browser_NavigationFailed(object sender, System.Windows.Navigation.NavigationFailedEventArgs e)
        {
            if (AdFailed != null && e.Exception != null)
            {
                AdFailed.Invoke(sender, e);
            }
            //Console.WriteLine("Browser_NavigationFailed");
        }

        void Browser_Navigating(object sender, NavigatingEventArgs e)
        {
            //LogService.WriteException("Browser_Naviagting", "uri change: " + e.Uri, null);

            if (e.Uri.AbsoluteUri.Contains(@""))
            {
                //20140427.. ..Pou：解決按下廣告後，沒有辦法正確導向指定Task的問題。
                TaskOSBrowser(e.Uri);
            }
            else
            {
                //20140427.. ..Pou：解決按下廣告後，沒有辦法正確導向指定Task的問題。
                if (e.Uri.AbsoluteUri.Contains("http") && e.Uri.AbsoluteUri.Contains("hodomobile") == false)
                {
                    string tUrl =
                        string.Format("",
                            AppID, e.Uri);
                    //WebBrowserTask webBrowserTask = new WebBrowserTask
                    //{
                    //    Uri = new Uri(tUrl, UriKind.Absolute)
                    //};
                    //webBrowserTask.Show();
                    TaskOSBrowser(new Uri(tUrl, UriKind.Absolute));
                }
                currentUri = e.Uri;
                //LogService.WriteException("Browser_Naviagting", "not contain: " + e.Uri, null);
            }
        }

        private void Browser_Navigated(object sender, NavigationEventArgs e)
        {
            //20140307.. ..Pou：增加出現載入失敗為空白時，需要通知為載入失敗的事件。
            //Dispatcher.BeginInvoke(() =>
            //{
            //    string tHtml = MiniBrowser.SaveToString();
            //    if (tHtml.Contains(AppID) == false)
            //    {
            //        if (AdError != null)
            //            AdError.Invoke("load ad error", e);
            //    }
            //});      
            //Console.WriteLine("Browser_Navigated");

            if (e.Uri.AbsoluteUri.Contains(@""))
            {
                //20140427.. ..Pou：解決按下廣告後，沒有辦法正確導向指定Task的問題。
                TaskOSBrowser(e.Uri);
            }
            else
            {
                //20140427.. ..Pou：解決按下廣告後，沒有辦法正確導向指定Task的問題。
                if (e.Uri.AbsoluteUri.Contains("http") && e.Uri.AbsoluteUri.Contains("hodomobile") == false)
                {
                    string tUrl =
                        string.Format("",
                            AppID, e.Uri);
                    //WebBrowserTask webBrowserTask = new WebBrowserTask
                    //{
                    //    Uri = new Uri(tUrl, UriKind.Absolute)
                    //};
                    //webBrowserTask.Show();
                    TaskOSBrowser(new Uri(tUrl, UriKind.Absolute));
                }
                currentUri = e.Uri;
                //LogService.WriteException("Browser_Naviagting", "not contain: " + e.Uri, null);
            }
        }

        void Browser_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            string tUri = string.Format("{0}{1}",
                             "", AppID);
            MiniBrowser.Navigate(new Uri(tUri, UriKind.Absolute));
            MiniBrowser.Visibility = System.Windows.Visibility.Collapsed;
            MiniBrowser.LoadCompleted += delegate
            {
                System.Windows.Threading.DispatcherTimer tTimer = new System.Windows.Threading.DispatcherTimer();
                tTimer.Interval = new TimeSpan(0, 0, 3);
                tTimer.Tick += delegate
                {
                    if (MiniBrowser != null)
                        MiniBrowser.Visibility = System.Windows.Visibility.Visible;
                    tTimer.Stop();
                    tTimer = null;
                };
                tTimer.Start();
                //Console.WriteLine(AppID + "_" + "LoadCompleted");
            };

            //20140505.. ..Pou：增加設定是否自動更新廣告的問題。
            if (gAudoRefresh)
            {
                gRefreshTimer = new System.Windows.Threading.DispatcherTimer();
                gRefreshTimer.Interval = new TimeSpan(0, 1, 0);
                gRefreshTimer.Tick += delegate
                {
                    if (MiniBrowser != null)
                        MiniBrowser.Navigate(new Uri(tUri, UriKind.Absolute));
                };
                gRefreshTimer.Start();
            }
        }

        private void UserControl_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Height = 70;
            this.MaxHeight = 71;

            //20140505.. ..Pou：增加沒有網路時的判斷。
            if (NetworkInterface.GetIsNetworkAvailable() == false)
            {
                this.Visibility = System.Windows.Visibility.Collapsed;
                MiniBrowser.NavigateToString("");
                if (AdError != null)
                    AdError.Invoke("No Network available!", e);
            }
            else
                this.Visibility = System.Windows.Visibility.Visible;
        }

        public void Dispose()
        {
            MiniBrowser.ClearCookiesAsync();
            MiniBrowser.ClearInternetCacheAsync();
            MiniBrowser = null;
            gRefreshTimer = null;
        }

        private void TaskOSBrowser(Uri pUri)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = pUri;
            webBrowserTask.Show();
        }

        #region 工具
        private async void WriteHtml(string pHtml)
        {
            try
            {
                byte[] tBytes = System.Text.Encoding.UTF8.GetBytes(pHtml);

                // Create a new file named DataFile.txt.
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
                    string.Format("{0}.txt", this.AppID),
                    CreationCollisionOption.ReplaceExisting);

                // Write the data from the textbox.
                using (var s = await file.OpenStreamForWriteAsync())
                {
                    s.Write(tBytes, 0, tBytes.Length);
                }
            }
            catch { }
        }

        private string IncludeJs()
        {
            string tJS = "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>"
                       + "<script>$(function() {"
                       + "var url = 'some_url';"
                       + "$.ajax(url, { statusCode: {  404: function() {  location.href='www.google.com';  }  } }); });"
                       + "</script>";

            return tJS;
        }
        #endregion
    }
}
